<template>
  <div class="video-player-container">
    <video ref="videoPlayerRef" class="video-js"></video>
  </div>
</template>

<script setup>
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';

const props = defineProps({
  src: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['error']);

const videoPlayerRef = ref();
const player = ref();

const waitingTimer = ref();

onMounted(() => {
  if (player.value) {
    player.value.dispose();
  }
  const options = {
    autoplay: false,
    controls: true,
    sources: [{ src: props.src, type: 'video/mp4' }],
  };
  console.log('options.......', options);
  player.value = videojs(videoPlayerRef.value, options, () => {
    console.log('onPlayerReady.......', player.value);
  });

  player.value.on('error', () => {
    console.log('error..........', player.value.error());
    emit('error', player.value.error());
  });

  player.value.on('playing', () => {
    console.log('playing..........', player.value);
    if (waitingTimer.value) {
      clearTimeout(waitingTimer.value);
    }
  });
  player.value.on('waiting', () => {
    console.log('waiting..........', player.value);
    if (waitingTimer.value) {
      clearTimeout(waitingTimer.value);
    }
    waitingTimer.value = setTimeout(() => {
      //player.value.play();
      player.value.pause();
      //抛出错误，加载超时
      emit('error', {
        code: 2,
        message: '加载超时(网络太差了.....)',
      });
      //emit('error',);
    }, 5 * 1000);
  });
});

onBeforeUnmount(() => {
  if (player.value) {
    player.value.dispose();
  }
  clearTimeout(waitingTimer.value);
});
</script>
<style>
.video-player-container {
  width: 100%;
  height: 100%;

  .video-js {
    width: 100%;
    height: 100%;
  }
}
</style>
